package com.example.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.example.common.exception.BusinessException;
import com.example.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT令牌校验拦截器
 * 解析token并将用户信息放入请求上下文中，方便在接口中直接获取用户ID
 */
@Slf4j
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    private static final String HEADER_TOKEN = "Authorization";
    private static final String USER_ID_HEADER = "userId";
    private static final String USERNAME_HEADER = "Username";
    
    // 不需要验证Token的路径
    private static final String[] WHITE_LIST = {
        "/lzw/auth/login",
        "/lzw/auth/captcha",
        "/lzw/user/login",    // 用户登录接口
        "/lzw/user/register", // 用户注册接口
        "/lzw/swagger-ui.html",
        "/lzw/swagger-resources",
        "/lzw/v2/api-docs",
        "/lzw/doc.html",
        "/lzw/webjars/",
        "/swagger-ui.html",
        "/swagger-resources",
        "/v2/api-docs",
        "/doc.html",
        "/webjars/"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 判断请求是否在白名单中
        String requestUri = request.getRequestURI();
        log.debug("拦截到请求: {}, 开始检查是否在白名单中", requestUri);
        
        for (String whitePath : WHITE_LIST) {
            if (requestUri.startsWith(whitePath)) {
                log.debug("请求 {} 匹配白名单 {}, 允许通过", requestUri, whitePath);
                return true;
            }
        }
        
        log.debug("请求 {} 不在白名单中, 开始验证登录状态", requestUri);
        
        // 解析token并检查登录状态
        try {
            if (StpUtil.isLogin()) {
                // 获取当前登录用户ID
                Long userId = SecurityUtils.getUserId();
                String username = SecurityUtils.getUsername();
                
                // 将用户信息放入请求头
                request.setAttribute("userId", userId);
                request.setAttribute("username", username);
                
                // 同时也放入请求头，便于跨服务调用
                response.setHeader(USER_ID_HEADER, String.valueOf(userId));
                response.setHeader(USERNAME_HEADER, username);
                
                log.debug("用户信息已放入请求上下文 - 用户ID: {}, 用户名: {}", userId, username);
                return true;
            } else {
                // 用户未登录，返回401状态码
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
        } catch (Exception e) {
            log.error("令牌解析异常", e);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }
} 